export const inBrowser = window !== 'undefined'

export function isFunction(val) {
  return typeof val === 'function'
}

function gen(name, mods) {
  if (!mods) {
    return ''
  }

  if (typeof mods === 'string') {
    return ` ${name}--${mods}`
  }

  if (Array.isArray(mods)) {
    return (mods).reduce(
      (ret, item) => ret + gen(name, item),
        ''
    )
  }
  return Object.keys(mods).reduce(
    (ret, key) => ret + (mods[key] ? gen(name, key) : ''),
    ''
  )
}

export function createBEM(name) {
  return (el, mods) => {
    if (el && typeof el !== 'string') {
      mods = el
      el = ''
    }

    el = el ? `${name}__${el}` : name
    return `${el}${gen(el, mods)}`
  }
}

export function createNamespace(
  name,
  prefix
) {
  name = `${prefix || 'rv'}-${name}`
  return [createBEM(name), name]
}

export function range(num, min, max) {
  return Math.min(Math.max(num, min), max)
}

function convertRem(value) {
  value = value.replace(/rem/g, '')
  return +value * getRootFontSize()
}

function convertVw(value) {
  value = value.replace(/vw/g, '')
  return (+value * window.innerWidth) / 100
}

function convertVh(value) {
  value = value.replace(/vh/g, '')
  return (+value * window.innerHeight) / 100
}

export function unitToPx(value) {
  if (typeof value === 'number') {
    return value
  }

  if (inBrowser) {
    if (value.indexOf('rem') !== -1) {
      return convertRem(value)
    }
    if (value.indexOf('vw') !== -1) {
      return convertVw(value)
    }
    if (value.indexOf('vh') !== -1) {
      return convertVh(value)
    }
  }

  return parseFloat(value)
}

export function preventDefault(
  event,
  isStopPropagation
) {
  /* istanbul ignore else */
  if (typeof event.cancelable !== 'boolean' || event.cancelable) {
  event.preventDefault()
}

if (isStopPropagation) {
  stopPropagation(event)
}
}

export function isObject(val){
  return val !== null && val === 'object'
}

export const extend = Object.assign
